import { useState, useEffect } from 'react';
import { Table, Button, Pagination, message } from 'antd';
import dayjs from 'dayjs';
import { accountList, delAccount } from '@/api/account';

const List = () => {
  const [tableData, setTableData] = useState([]);
  const [total, setTotal] = useState(0);
  const [formdata, setFormdata] = useState({
    currentPage: 1,
    pageSize: 10
  });

  // 获取列表数据
  const getList = async () => {
    try {
      const res = await accountList(formdata);
      setTableData(res.data || []);
      setTotal(res.total || 0);
    } catch (error) {
      console.error('获取数据失败', error);
      message.error('获取数据失败');
    }
  };

  useEffect(() => {
    getList();
  }, [formdata.currentPage, formdata.pageSize]);

  // 日期格式化
  const formatTime = (text) => {
    return dayjs(text).format('YYYY-MM-DD HH:mm:ss');
  };

  // 删除用户
  const del = async (id) => {
    console.log(id);
    try {
      const res = await delAccount({ id });
      console.log(res);
      if (res.code === 0) {
        message.success('删除成功');
        getList();
      } else {
        message.error('删除失败');
      }
    } catch (error) {
      console.error('删除失败', error);
      message.error('删除失败');
    }
  };

  // 表格列配置
  const columns = [
    {
      title: '序号',
      dataIndex: 'id',
      key: 'id',
    },
    {
      title: '账号',
      dataIndex: 'account',
      key: 'account',
    },
    {
      title: '用户',
      dataIndex: 'userGroup',
      key: 'userGroup',
    },
    {
      title: '创建时间',
      dataIndex: 'ctime',
      key: 'ctime',
      render: (text) => formatTime(text),
    },
    {
      title: '操作',
      key: 'action',
      width: 180,
      render: (_, record) => (
        <>
          <Button type="primary" size="small" onClick={() => editbtn(record)} style={{ marginRight: 8 }}>
            编辑
          </Button>
          <Button type="primary" danger size="small" onClick={() => del(record.id)}>
            删除
          </Button>
        </>
      ),
    },
  ];

  // 分页变化处理
  const handlePageChange = (page, pageSize) => {
    setFormdata({
      currentPage: page,
      pageSize,
    });
  };

  return (
    <div>
      <Table
        columns={columns}
        dataSource={tableData}
        rowKey="id"
        pagination={false}
      />
      <div style={{ marginTop: 30, textAlign: 'right' }}>
        <Pagination
          current={formdata.currentPage}
          pageSize={formdata.pageSize}
          pageSizeOptions={[5, 10, 20, 30]}
          total={total}
          showSizeChanger
          showQuickJumper
          showTotal={(total) => `共 ${total} 条`}
          onChange={handlePageChange}
          onShowSizeChange={(current, size) => handlePageChange(1, size)}
        />
      </div>
    </div>
  );
};

export default List;